import {getValueFromUrl} from "./utils.js"

function getNewsDetail(nid) {
    // 获得浏览器地址栏的参数
    $.ajax({
        url: "http://www.woniu-news.com:8082/newsDetail.php",
        type: "GET",
        xhrFields: {
            withCredentials: true
        },
        data: {
            nid
        },
        dataType: "json",
        success: (resp) => {
            if (resp.code === 200) {
                if (resp.data.newImg) {
                    const img = `<img class="news-img" width="500" src="${resp.data.newImg}" alt="新闻图片">`
                    $("div.news-img").html(img)
                }
                $("#title").val(resp.data.title)
                $("#content").val(resp.data.context)
            }
        },
        error: (resp) => {
            alert(resp.message)
        }
    })
}

function updateNews(nid) {
    const title = $("#title").val()
    const context = $("#content").val()
    $.ajax({
        url: "http://www.woniu-news.com:8082/editNews.php",
        type: "POST",
        xhrFields: {
            withCredentials: true
        },
        data: {
            nid,
            title,
            context
        },
        dataType: "json",
        success: (resp) => {
            if (resp.code === 200) {
                alert(resp.message)
                window.location.href = "news_management.html"
            } else {
                alert(resp.message)
            }
        },
        error: (resp) => {
            alert(resp.message)
        }
    })
}

const nid = getValueFromUrl("nid")
getNewsDetail(nid)

$(".update").click(() => {
    updateNews(nid)
})